package com.mqb.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.mqb.config.mixin.CustomModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.security.jackson2.CoreJackson2Module;
import org.springframework.security.jackson2.SecurityJackson2Modules;
import org.springframework.security.web.jackson2.WebJackson2Module;
import org.springframework.security.web.jackson2.WebServletJackson2Module;
import org.springframework.security.web.server.jackson2.WebServerJackson2Module;

/**
 * @author mqb
 * @date 2021/4/7 9:27
 */
@Configuration
public class CustomRedisConfig {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Bean
    public RedisSerializer<Object> redisSerializer() {
        ObjectMapper om = objectMapper.copy();

        om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        om.registerModule(new CoreJackson2Module());
        om.registerModule(new WebJackson2Module());
        om.registerModule(new WebServletJackson2Module());
        om.registerModule(new WebServerJackson2Module());

        om.registerModule(new CustomModule());

        SecurityJackson2Modules.enableDefaultTyping(om);
        return new GenericJackson2JsonRedisSerializer(om);
    }

    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(factory);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setDefaultSerializer(redisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
}
